﻿#include "pch.h"
#include "Const.h"
#include "Game.h"
#include "Man.h"

/**
 * 构造方法。
 * @param back      背后对象
 * @param drawer    绘图者
 * @param gameBoard 游戏区域
 * @param type      类型
 * @param x, y      左上角坐标
 */
Man::Man(BaseGameObject* back, HDC drawer, CWnd* gameBoard, Type type, int x, int y) :
    Box(back, drawer, type, x, y), 
    mGameBoard(gameBoard), 
    mCurrentImage1(&mImage), 
    mCurrentImage2(&mImage2) {
    // 加载所有图片
    CString imageFilePath;

    imageFilePath.Format(Const::IMAGE_FILE_PATH, type * 10 + 2);
    mImageLeft1.Load(imageFilePath);

    imageFilePath.Format(Const::IMAGE_FILE_PATH, type * 10 + 3);
    mImageLeft2.Load(imageFilePath);

    imageFilePath.Format(Const::IMAGE_FILE_PATH, type * 10 + 4);
    mImageRight1.Load(imageFilePath);

    imageFilePath.Format(Const::IMAGE_FILE_PATH, type * 10 + 5);
    mImageRight2.Load(imageFilePath);

    imageFilePath.Format(Const::IMAGE_FILE_PATH, type * 10 + 6);
    mImageUp1.Load(imageFilePath);

    imageFilePath.Format(Const::IMAGE_FILE_PATH, type * 10 + 7);
    mImageUp2.Load(imageFilePath);

    // 开始跳舞
    SetTimer(mGameBoard->GetSafeHwnd(), (UINT_PTR)this, Const::TIMER_INIT, OnTimer);
}

/**
 * 析构方法。
 */
Man::~Man() {
    // 停止定时器
    KillTimer(mGameBoard->GetSafeHwnd(), (UINT_PTR)this);
}

/**
 * 跳舞。
 */
void Man::Dancing() {
    if (mCurrentImage == mCurrentImage1) {
        mCurrentImage = mCurrentImage2;
    } else {
        mCurrentImage = mCurrentImage1;
    }
    mCurrentImage->BitBlt(mDrawer, mX * Const::GRID_SIZE, mY * Const::GRID_SIZE);
    mGameBoard->Invalidate(FALSE);
}

/**
 * 移动。
 * @param direction     方向
 * @param moveResult    移动结果
 * @return 被推动的箱子
 */
BaseGameObject* Man::Move(UINT direction, MoveResult* moveResult) {
    int destX = mX, destY = mY; // 新位置的坐标

    // 根据方向，计算新位置的坐标和图片
    switch (direction) {
        case VK_DOWN:
            destY++;
            mCurrentImage1 = &mImage;
            mCurrentImage2 = &mImage2;
            break;
        case VK_LEFT:
            destX--;
            mCurrentImage1 = &mImageLeft1;
            mCurrentImage2 = &mImageLeft2;
            break;
        case VK_RIGHT:
            destX++;
            mCurrentImage1 = &mImageRight1;
            mCurrentImage2 = &mImageRight2;
            break;
        case VK_UP:
            destY--;
            mCurrentImage1 = &mImageUp1;
            mCurrentImage2 = &mImageUp2;
            break;
    }

    // 重新设置图片
    mCurrentImage = mCurrentImage1;

    // 先移动旁边的物体
    BaseGameObject* box = Game::sBaseGameObjects[destY][destX]->Move(direction, moveResult);
    if (*moveResult == NO_MOVE) {
        return box;
    }

    // 移动小人
    Box::Move(direction, moveResult);

    return box;
}

/**
 * 定时器事件的响应方法。
 * @param timerId   定时器 id
 */
void CALLBACK Man::OnTimer(HWND, UINT, UINT_PTR timerId, DWORD) {
    Man* man = (Man*)timerId;
    man->Dancing();
}
